package com.sgb.kjwl.viewmodel.transport;

import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2020/12/29 18:14
 * @Description:
 */
public class CargoPublishCarInfoViewModel extends AndroidViewModel {
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarLen = new MutableLiveData<>();

    public CargoPublishCarInfoViewModel(@NonNull Application application) {
        super(application);
    }

    /**
     * 获取车型车长
     */
    public void getCarTypeAndLen(Context context, String goodsTypeNo) {
        DialogHelper.showProgressDialog(context, "数据加载中...");
        NewAPIManager.getInstance().getLogisticsAPI().getCarTypeAndLen(goodsTypeNo).enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                //获取全部车长并填充数据
                if (data == null || data.getData() == null) return;
                ldCarType.postValue(data.getData());
                //填充数据
                List<GoodsInfoTypeEntity3> lenList = new ArrayList<>();
                for (GoodsInfoTypeEntity3 type : data.getData()) {
                    if (type.getCarLenList() == null) continue;
                    lenList.addAll(type.getCarLenList());
                }
                //去重
                lenList = removeDuplicate(lenList);
                ldCarLen.postValue(lenList);
            }
        });
    }

    /**
     * 车长去重
     */
    private List<GoodsInfoTypeEntity3> removeDuplicate(List<GoodsInfoTypeEntity3> list) {
        List<GoodsInfoTypeEntity3> result = new ArrayList<>();
        for (GoodsInfoTypeEntity3 entity : list) {
            boolean isDuplicate = false;
            for (GoodsInfoTypeEntity3 len : result) {
                //判断当前车长是否重复
                if (!TextUtils.isEmpty(len.getName()) && len.getName().equals(entity.getName())) {
                    isDuplicate = true;
                    break;
                }
            }
            //未重复则加入返回数据中
            if (!isDuplicate) {
                result.add(entity);
            }
        }
        return result;
    }
}
